package com.ychong.library.view

import android.content.Context
import android.content.res.TypedArray
import android.graphics.*
import android.os.Build
import android.text.Editable
import android.text.InputType
import android.text.TextWatcher
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import androidx.appcompat.widget.AppCompatEditText
import com.ychong.library.R
import com.ychong.library.utils.ResUtils
import com.ychong.library.utils.ScreenUtils


open class YCHEditText : AppCompatEditText, View.OnFocusChangeListener, TextWatcher {

    private var invisibleId: Int
    private var visibleId: Int
    private var clearId: Int
    private var clearBitmap: Bitmap? = null
    private var visibleBitmap: Bitmap? = null
    private var invisibleBitmap: Bitmap? = null
    private var showVisibleBitmap: Bitmap? = null
    private var visibleWidth: Int = 0
    private var visiblePadding: Int = 0
    private var editFrameStyle: Int = 1
    private var editFrameColor: Int = 0
    private var editBorderWidth:Int = 0

    private var paint: Paint? = null
    private var isPasswordType: Boolean = false

    constructor(context: Context) : this(context,null)
    constructor(context: Context, attributeSet: AttributeSet?) : this(context, attributeSet,0)
    constructor(context: Context, attributeSet: AttributeSet?, defStyle: Int) : super(
        context,
        attributeSet,
        defStyle
    ) {
        val array: TypedArray =
            context.obtainStyledAttributes(
                attributeSet, R.styleable.YCHEditText, defStyle,
                0
            )
        //获取清除图标资源
        clearId = array.getResourceId(
            R.styleable.YCHEditText_clearDrawable,
            R.mipmap.ic_clear
        )
        //获取可见图标资源
        visibleId = array.getResourceId(
            R.styleable.YCHEditText_visibleDrawable,
            R.mipmap.ic_show
        )
        //获取不可见图标资源
        invisibleId = array.getResourceId(
            R.styleable.YCHEditText_invisibleDrawable,
            R.mipmap.ic_hide
        )
        //可见图标按钮默认宽
        visibleWidth = array.getDimensionPixelSize(
            R.styleable.YCHEditText_visibleDrawableWidth,
            ScreenUtils.dpToPx(15)
        )
        //边框宽度
        editBorderWidth = array.getDimensionPixelSize(R.styleable.YCHEditText_editBorderWidth,ScreenUtils.dpToPx(0))
        //可见图标按钮默认内边距
        visiblePadding = array.getDimensionPixelSize(
            R.styleable.YCHEditText_visibleDrawableSpacing,
            ScreenUtils.dpToPx(5)
        )
        //输入框边框样式
        editFrameStyle = array.getInt(R.styleable.YCHEditText_editFrameStyle, 1)
        //输入框边框颜色
        editFrameColor =
            array.getColor(
                R.styleable.YCHEditText_editFrameColor,
                ResUtils.getColor(context, R.color.color_0D71DF)
            )
        array.recycle()
        init()
    }

    private fun init() {


        clearBitmap = createBitmap(clearId)
        visibleBitmap = createBitmap(visibleId)
        invisibleBitmap = createBitmap(invisibleId)

        showVisibleBitmap = invisibleBitmap

        //是否是密码样式
        //是否是密码样式
        isPasswordType =
            inputType == InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_CLASS_TEXT

        paint = Paint()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        if (isPasswordType){
            setPadding(paddingLeft, paddingTop, (visiblePadding * 4 + visibleWidth * 2), paddingBottom)
        }else{
            setPadding(paddingLeft, paddingTop, (visiblePadding * 2 + visibleWidth), paddingBottom)
        }

    }

    override fun onDraw(canvas: Canvas?) {
        super.onDraw(canvas)
        paint!!.style = Paint.Style.STROKE
        //绘制边框
        drawBorder(canvas)

        //绘制清空和明文显示图标
        drawIcon(canvas)
    }

    private fun drawBorder(canvas: Canvas?) {
        var borderWidth:Float = 0f
        if (editBorderWidth!=0){
            paint!!.color = editFrameColor
            //获取焦点时，加粗边框
            borderWidth = if (isFocused) {
                editBorderWidth*2f
            } else {
                editBorderWidth*1f
            }
        }else{
            paint!!.color = Color.WHITE
        }
        paint!!.strokeWidth = borderWidth
        background = null
        when (editFrameStyle) {
            1 -> {
                //矩形
                canvas!!.drawRect(
                    borderWidth / 2,
                    borderWidth / 2,
                    width * 1f - (borderWidth / 2),
                    height * 1f - (borderWidth / 2),
                    paint!!
                )
            }
            2 -> {
                //圆角矩形
                if (Build.VERSION.SDK_INT >= 21) {
                    canvas!!.drawRoundRect(
                        borderWidth / 2,
                        borderWidth / 2,
                        width * 1f - (borderWidth / 2),
                        height * 1f - (borderWidth / 2),
                        10f,
                        10f,
                        paint!!
                    )
                } else {
                    val rectF = RectF(
                        borderWidth / 2,
                        borderWidth / 2,
                        width * 1f - (borderWidth / 2),
                        height * 1f - (borderWidth / 2)
                    )
                    canvas!!.drawRoundRect(rectF, 10f, 10f, paint!!)
                }

            }
            3 -> {
                //半矩形
                canvas!!.drawLine(0f, height * 1f, width * 1f, height * 1f, paint!!)
                canvas.drawLine(0f, height / 2f, 0f, height * 1f, paint!!)
                canvas.drawLine(width * 1f, height / 2f, width * 1f, height * 1f, paint!!)

            }
            4 -> {

            }
        }
    }

    private fun drawIcon(canvas: Canvas?) {
        if (isFocused && text!!.isNotEmpty()) {
            val left = width - visiblePadding - visibleWidth
            val top = (height - visibleWidth) / 2
            val right = width - visiblePadding
            val bottom = (height + visibleWidth) / 2

            if (isPasswordType) {
                //绘制显示明文图标
                val visibleRect = Rect(
                    left,
                    top,
                    right,
                    bottom
                )
                canvas!!.drawBitmap(showVisibleBitmap!!, null, visibleRect, paint)

                //绘制清空图标
                val clearRect = Rect(
                    left - visiblePadding - visibleWidth,
                    top,
                    left - visiblePadding,
                    bottom
                )
                canvas.drawBitmap(clearBitmap!!, null, clearRect, paint)
            } else {
                //绘制清空图标
                val clearRect = Rect(
                    left,
                    top,
                    right,
                    bottom
                )
                canvas!!.drawBitmap(clearBitmap!!, null, clearRect, paint)
            }

        }


    }

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        if (event!!.action == MotionEvent.ACTION_DOWN) {
            val x = event.x
            val y = event.y
            if (isFocused) {
                if (isPasswordType) {
                    //确定点击了清空图标
                    if (x > (width - visiblePadding * 3 - visibleWidth * 2)
                        && x < (width - visiblePadding * 2 - visibleWidth)
                    ) {
                        clear()
                    }
                    //确定点击了显示文本图标
                    if (x > (width - visiblePadding * 2 - visibleWidth)
                        && x < width
                    ) {
                        inputType =
                            if (inputType == InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_CLASS_TEXT) {
                                showVisibleBitmap = visibleBitmap
                                InputType.TYPE_CLASS_TEXT
                            } else {
                                showVisibleBitmap = invisibleBitmap
                                InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_CLASS_TEXT
                            }
                        setSelection(text!!.length)
                        invalidate()
                    }
                } else {
                    //确定点击了清空图标
                    if (x > (width - visiblePadding * 2 - visibleWidth)
                        && x < width
                    ) {
                        clear()
                    }
                }

            }
        }
        return super.onTouchEvent(event)
    }

    private fun clear(){
        text = null
        showVisibleBitmap = invisibleBitmap
    }

    override fun onFocusChange(v: View?, hasFocus: Boolean) {
    }

    override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
    }

    override fun afterTextChanged(s: Editable?) {

    }

    override fun onTextChanged(
        text: CharSequence?,
        start: Int,
        lengthBefore: Int,
        lengthAfter: Int
    ) {
        super.onTextChanged(text, start, lengthBefore, lengthAfter)
    }

    private fun createBitmap(resId: Int): Bitmap {
        return BitmapFactory.decodeResource(context.resources, resId)
    }

}